package itsm.isperp.framework.message.impl;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.message.IMessageSender;
import itsm.isperp.framework.message.domain.IMessagePacket;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.commons.lang3.StringUtils;

public class EmailSender implements IMessageSender {

	public static final String BEAN_ID = "isperp.emailSender";
	private Session session;

	private static boolean SESSION_REFRESH = false;

	public static void refreshCache() {
		SESSION_REFRESH = true;
	}

	@Override
	public void send(IMessagePacket message) throws Exception {
		this.sendMail(message, null);
	}

	/**
	 * 发送邮件
	 * 
	 * @param message
	 * @param files
	 * @throws Exception
	 */
	public void sendMail(IMessagePacket message, Collection<File> files)
			throws Exception {
		System.out.print("--------------邮件发送--------------");
		System.out.print(message);
		Session session = this.getMailSession();
		MimeMessage mimeMsg = new MimeMessage(session);
		if (message.getTitle() != null) {
			mimeMsg.setSubject(MimeUtility.encodeText(message.getTitle(),
					"UTF-8", "B"));
		}
		// String tempAccount = ContextHolder.getConfigByKey("mailServer")
		// .replace("smtp.", "@");
		// System.out.print(ContextHolder
		// .getConfigByKey("mailAccount"));
		mimeMsg.setFrom(new InternetAddress(ContextHolder
				.getConfigByKey("mailAddress")));

		if (StringUtils.isNotEmpty(message.getReceiver())) {
			List<InternetAddress> addressList = new ArrayList<InternetAddress>();

			addressList.add(new InternetAddress(message.getReceiverAddress()));

			InternetAddress[] addressArray = new InternetAddress[addressList
					.size()];
			addressList.toArray(addressArray);
			mimeMsg.setRecipients(javax.mail.Message.RecipientType.TO,
					addressArray);
		} else {
			throw new IllegalArgumentException("Mail [receivers] not assigned.");
		}

		Multipart multipart = new MimeMultipart();
		if (message.getContent() != null) {
			MimeBodyPart mimeBodyPartMessage = new MimeBodyPart();
			// 加上邮件签名
			String Content_ = message.getContent();
			String emailSign = ContextHolder.getConfigByKey("emailSign");
			if (StringUtils.isNotEmpty(emailSign)) {
				Content_ += emailSign;
			}
			mimeBodyPartMessage
					.setContent(Content_, "text/html; charset=utf-8");
			multipart.addBodyPart(mimeBodyPartMessage);
		}

		if (files != null && files.size() > 0) {
			for (File file : files) {
				if (null == file || !file.exists() || file.isDirectory()) {
					continue;
				}
				String filename = file.getName();
				String encodedFilename = MimeUtility.encodeText(filename);
				MimeBodyPart mimeBodyPartFile = new MimeBodyPart();
				DataSource dsFile = new FileDataSource(file);
				mimeBodyPartFile.setDataHandler(new DataHandler(dsFile));
				mimeBodyPartFile.setFileName(encodedFilename);
				multipart.addBodyPart(mimeBodyPartFile);

			}
		}
		mimeMsg.setContent(multipart);
		mimeMsg.setSentDate(new Date());
		Transport.send(mimeMsg);
	}

	/**
	 * 获取有效的缓存
	 * 
	 * @return
	 */
	private Session getMailSession() {
		if (session == null || SESSION_REFRESH == true) {
			resetSession();
		}
		return session;
	}

	private void resetSession() {

		SESSION_REFRESH = false;
		String mailPort="25";
		if(ContextHolder.getConfigByKey("txtMailPort")!=null)
		  mailPort=ContextHolder.getConfigByKey("txtMailPort");
		Properties properties = new Properties();
		properties.put("mail.transport.protocol", "smtp");
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.port", mailPort);
		properties.put("mail.host", ContextHolder.getConfigByKey("mailServer"));

		session = Session.getDefaultInstance(properties, new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(ContextHolder.getConfigByKey(
						"mailAccount"), ContextHolder
						.getConfigByKey("mailPassword"));
			}
		});
	}
}
